package com.cndw.kungfu.controller;

import java.util.HashMap;
import java.util.Map;

import com.cndw.kungfu.comm.PositionInspection;
import com.cndw.kungfu.comm.tencent.LogFieldType;
import com.cndw.kungfu.comm.tencent.QQDC;
import com.cndw.kungfu.config.Constants;
import com.cndw.kungfu.config.ConstantsCost;
import com.cndw.kungfu.config.ConstantsDailyItem;
import com.cndw.kungfu.config.ConstantsDayIntKey;
import com.cndw.kungfu.config.ConstantsLog;
import com.cndw.kungfu.config.ConstantsModel;
import com.cndw.kungfu.config.ConstantsRadio;
import com.cndw.kungfu.config.GoodsEffectConfig;
import com.cndw.kungfu.domain.GoodsMode;
import com.cndw.kungfu.domain.MonsterDeploy;
import com.cndw.kungfu.domain.Player;
import com.cndw.kungfu.domain.Scene;
import com.cndw.kungfu.ext.LanguageLib;
import com.cndw.kungfu.ext.TimeProcesser;
import com.cndw.kungfu.model.Context;
import com.cndw.kungfu.model.activity.domain.WorldBoos;
import com.cndw.kungfu.model.battle.Battle;
import com.cndw.kungfu.model.battle.FighterMonster;
import com.cndw.kungfu.model.sys.LogServer;
import com.cndw.kungfu.vo.EventNotice;
import com.cndw.rpg.annotation.Controller;
import com.cndw.rpg.framework.ResponseMessage;
import com.cndw.rpg.framework.Session;

/**
 * 世界boss接口
 * 
 * @author fantadust [9677889@qq.com]
 * @date 2012-5-12 下午7:15:34
 */
@Controller
public class BossController {

	/**
	 * 进入场景时候加载数据
	 * 
	 * @param session
	 * @param boosId
	 * @return
	 */
	public ResponseMessage bossSceneLoad(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());

		WorldBoos worldBoos = WorldBoos.getBySceneId(player.getSceneId());
		if (worldBoos != null) {
			worldBoos.broadcastOrder(session.getUid());
		}

		QQDC.getInstance().logClick(player, LogFieldType.worldBoss);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("onceGold", ConstantsModel.bossBuffOnceGold);
		map.put("reviveGold", ConstantsModel.bossReviveGold);
		map.put("buffAdd", worldBoos == null ? 0 : worldBoos.getPlayerBuff(session.getUid()));
		map.put("reviveTime", worldBoos == null ? 0 : worldBoos.playerDeadGet(session.getUid()));
		map.put("akTimes", worldBoos == null ? 0 : worldBoos.getAkTimes(session.getUid()));
		map.put("myDam", worldBoos == null ? 0 : worldBoos.getDamById(session.getUid()));
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 进行战斗
	 * 
	 * @param id
	 * @return
	 */
	public ResponseMessage challenge(Session session, int monsterDeployId) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		MonsterDeploy monsterDeploy = Context.getUndercityServer().getDeployById(monsterDeployId);
		if (monsterDeploy == null) {
			return null;
		}
		if (PositionInspection.checkMonster(player, monsterDeploy) == false) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.position.err"));
		}
		Scene scene = Context.getSceneServer().getSceneById(monsterDeploy.getSceneId());

		int noKill = Constants.playerState1_battle | Constants.playerState2_learn | Constants.playerState4_slaughter;

		if (player.stateContains(noKill)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.err.cooling"));
		}
		if (player.stateContains(Constants.playerState1024_aiUndercity)) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("undercity.ai.err"));
		}

		WorldBoos worldBoos = WorldBoos.getById(monsterDeploy.getRefreshApp());
		if (worldBoos == null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.sys"));
		}
		if (worldBoos.playerDeadGet(session.getUid()) > TimeProcesser.getUnixTime()) {
			return null;
		}
		if (player.getLevel() < worldBoos.getLevel()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("activity.boss.errlevel", worldBoos.getLevel()));
		} else if (player.getLevel() > worldBoos.getLevelMax()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("activity.boss.errlevel2", worldBoos.getLevelMax()));
		} else if (player.getTeam() != null) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("team.err.controlontem"));
		}
		FighterMonster bossFighter = worldBoos.getBossFighter();
		if (bossFighter == null || bossFighter.getHp() <= 0) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("activity.boos.dead"));
		} else if (!worldBoos.isCanBattle()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("activity.boos.timeover"));
		}

		int battleId = player.getDataInfo().getBattleId();
		if (battleId > 0) {
			Battle battle = Context.getDataServer().getBattleMap().get(battleId);
			if (battle != null) {
				if (battle.getEndTime() > TimeProcesser.getUnixTime()) {
					return ResponseMessage.ticpErrMsg(LanguageLib.get("battle.err.cooling"));
				}
				if (battle.isAllReceive() || battle.getAllPlayers().size() == 1) {
					battle.clear();
				}
			}
		}
		int coefficient = worldBoos.getPlayerBuff(player.getPlayerId());
		Battle battle = new Battle(player.getLikedFighter(coefficient), worldBoos.getBossFighter());
		battle.config(1, scene.getType(), worldBoos.getAkTimes(player.getPlayerId()));
		battle.setDefaultMonsterId(monsterDeploy.getDefaultMonsterId());
		battle.execBattle(Constants.battle_pve);
		battle.deployReport(monsterDeployId);
		battle.broadcast();
		// battle.clear();

		if (battle.getSourceDam() > 0) {
			player.getDataInfo().getEveryDay().finishDailyItem(ConstantsDailyItem.challengeWorldBossItem);
			if (worldBoos.isFirst(player.getPlayerId())) {// 只在首次打出伤害时候记录
				if (worldBoos.getId() == 1) {
					player.getDataInfo().alterExpRet(Constants.expRet_boosYtz);// 参加活动标记
				} else if (worldBoos.getId() == 2) {
					player.getDataInfo().alterExpRet(Constants.expRet_boosBear);// 参加活动标记
				} else {
					player.getDataInfo().alterExpRet(Constants.expRet_boosCyh);// 参加活动标记
				}
			}

			worldBoos.damIncrement(player.getPlayerId(), battle.getSourceDam());
			if (worldBoos.getBossFighter().getHp() <= 0) {// boss死亡
				worldBoos.checkDead(battle.getCostTime(), player.getPlayerId());// 检查怪物死亡后的事件
				worldBoos.broadcastDead();
			}
		}
		if (battle.getWiner() != 1) {
			worldBoos.playerDeadSet(session.getUid(), TimeProcesser.getUnixTime() + battle.getCostTime() + 32);
		}

		player.stateAdd(Constants.playerState1_battle);
		Context.getPlayerServer().broadcaseState(player);
		player.getDataInfo().setBattleId(battle.getId());

		Map<String, Object> map = new HashMap<String, Object>();
		map.put("akTimes", worldBoos.getAkTimes(session.getUid()));
		map.put("myDam", worldBoos.getDamById(session.getUid()));

		QQDC.getInstance().logClick(player, LogFieldType.battleBoss);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 领取世界boss 武道令奖励
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage gotToken(Session session) {

		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		int dailyItem = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.dailyItem);
		boolean isOk = (dailyItem & (1 << ConstantsDailyItem.challengeWorldBossItem)) > 0;
		if (!isOk) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("boss.token.no"));
		}
		int haveGot = player.getDataInfo().getEveryDay().intDataGet(ConstantsDayIntKey.tokenGot);
		boolean gotNoSign = (haveGot & Constants.tokenBoss) <= 0;
		if (!gotNoSign) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("boss.token.over"));
		}

		if (!player.getPlayerBoxs().checkBlack()) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.player.boxmin", 1));
		}
		GoodsMode goodsMode = Context.getGoodsServer().getModeById(GoodsEffectConfig.warTokenGoodsId);
		player.getDataInfo().getEveryDay().intDataSet(ConstantsDayIntKey.tokenGot, haveGot | Constants.tokenBoss);
		player.getDataInfo().commitSync();
		Context.getGoodsServer().giveGoodsBing(session.getUid(), GoodsEffectConfig.warTokenGoodsId, 1, 1);
		LogServer
				.recordLog(player, ConstantsLog.goods, 70022, 2, 1, player.getPlayerBoxs().getStackNum(GoodsEffectConfig.warTokenGoodsId), goodsMode.getName());

		Map<String, Object> map = new HashMap<String, Object>();
		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * buff
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage buff(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		WorldBoos worldBoos = WorldBoos.getBySceneId(player.getSceneId());
		if (worldBoos == null) {
			return null;
		}
		int currentTime = TimeProcesser.getUnixTime();
		int beginTime = TimeProcesser.getMorningTime() + worldBoos.getRefreshTime();
		int entTime = worldBoos.getLastClac();
		if (entTime == 0 || entTime < beginTime) {
			entTime = currentTime + WorldBoos.bossLifeTime;
		}
		if (currentTime <= beginTime - 600 || currentTime >= entTime) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("boss.buff.time"));
		}

		int buffNow = worldBoos.getPlayerBuff(session.getUid());
		if (buffNow >= ConstantsModel.bossBuffMax) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("boss.buff.max"));
		}
		int haveTool = player.getPlayerBoxs().getStackNum(GoodsEffectConfig.buffGoodsId);
		boolean costTool = haveTool > 0 ;
		if (haveTool<=0 && player.getGoldAll() < ConstantsModel.bossBuffOnceGold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		if (haveTool > 0) {
			player.getPlayerBoxs().costGoods(GoodsEffectConfig.buffGoodsId, 1);
			haveTool--;
		}else {
			player.alterGoldAll(-ConstantsModel.bossBuffOnceGold);
			LogServer.costEventLog(session.getUid(), ConstantsModel.bossBuffOnceGold, ConstantsCost.bossBuff);
		}
		
		player.commitSync();
		buffNow += ConstantsModel.bossBuffOnceAdd;
		worldBoos.playerBuffSet(session.getUid(), buffNow);
		
		EventNotice notice = new EventNotice(ConstantsRadio.battle, ConstantsRadio.battle_BuffAdd);
		notice.put("playerId", player.getPlayerId());
		notice.put("buffNow", buffNow);
		notice.broadcastScene(player);
		
		LogServer.recordLog(player, ConstantsLog.battle, 40101,costTool?0:ConstantsModel.bossBuffOnceGold, true, buffNow,costTool,haveTool);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		map.put("buffAdd", buffNow);
		map.put("suc", true);
		map.put("costTool", costTool);

		return ResponseMessage.getSuccMessage(map);
	}

	/**
	 * 复活
	 * 
	 * @param session
	 * @return
	 */
	public ResponseMessage revive(Session session) {
		Player player = Context.getPlayerServer().getByPlayerId(session.getUid());
		WorldBoos worldBoos = WorldBoos.getBySceneId(player.getSceneId());
		if (worldBoos == null) {
			return null;
		}
		if (player.getGoldAll() < ConstantsModel.bossReviveGold) {
			return ResponseMessage.ticpErrMsg(LanguageLib.get("comm.err.gold"));
		}
		worldBoos.playerDeadSet(session.getUid(), 0);
		player.alterGoldAll(-ConstantsModel.bossReviveGold);
		player.commitSync();

		LogServer.costEventLog(session.getUid(), ConstantsModel.bossReviveGold, ConstantsCost.bossRevive);
		LogServer.recordLog(player, ConstantsLog.battle, 40102, ConstantsModel.bossReviveGold);
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("gold", player.getGold());
		map.put("goldBing", player.getGoldBing());
		return ResponseMessage.getSuccMessage(map);
	}
}
